export default {
	namespaced: true,

	state: {
		goodsInfo: uni.getStorageSync('goodsInfo') || []
	},

	getters: {
		goodsInfo: state => state.goodsInfo,
		count: state => state.goodsInfo.filter(item => item.goods_state === true).reduce((sum, item) => sum += item.goods_number, 0),
		amount: state => state.goodsInfo.filter(item => item.goods_state === true).reduce((sum, item) => (sum += item.goods_number * item.goods_price), 0).toFixed(2),
		selectAll: state => state.goodsInfo.every(item => item.goods_state)
	},

	mutations: {
		// 全选反选
		checkedAll (state, value) {
			state.goodsInfo.forEach(item => item.goods_state = value)

			uni.setStorageSync('goodsInfo', state.goodsInfo)
		},

		// 删除商品
		removeGoods (state, goods) {
			const index = state.goodsInfo.findIndex(item => item.goods_id = goods.goods_id)

			if (index > -1) {
				state.goodsInfo.splice(index, 1)
			}

			uni.setStorageSync('goodsInfo', state.goodsInfo)
		},

		// 更新数量
		updateGoodsNum (state, payload) {
			const find = state.goodsInfo.find(item => item.goods_id === payload.goods_id)
			if (find) {
				find.goods_number = payload.goods_number
			}

			uni.setStorageSync('goodsInfo', state.goodsInfo)
		},



		// 更新选中状态
		updateGoodsState (state, payload) {
			const find = state.goodsInfo.find(item => item.goods_id === payload.goods_id)
			if (find) {
				find.goods_state = payload.goods_state
			}

			uni.setStorageSync('goodsInfo', state.goodsInfo)
		},

		// 加入购物车
		setGoodsInfo (state, payload) {
			const flag = state.goodsInfo.find(item => item.goods_id === payload.goods_id)
			if (flag) {
				flag.goods_number += payload.goods_number
			} else {
				state.goodsInfo.unshift(payload)
			}

			uni.setStorageSync('goodsInfo', state.goodsInfo)
		}
	}
}